#!/usr/bin/lua
-- lua parse.lua -f example.dos
--print(package.cpath)
--os.exit(0)
local lt = require("ltreesitter")

-- 处理命令行参数
local args = { ... }
local content = ""
if args[1] then
  -- 从文件读取内容
  local file = io.open(args[1], "r")
  if file then
    content = file:read("*all")
    file:close()
  else
    error("无法打开文件: " .. args[2])
  end
else
  io.stderr:write("请在参数中指定文件路径")
  os.exit(1)
end

-- Create a parser
local parser = lt.require("dolphindb")
--local parser = lt.load("./dolphindb.so", "dolphindb")

-- Parse the content
local tree = parser:parse_string(content)
-- 检查 tree 是否为 nil
if not tree then
  error("解析内容失败")
end

-- 获取根节点
local root = tree:root()

-- 遍历首层元素并打印出 comment 类型的元素
--print(type(root))
for child in root:children() do
  if child:type() == "comment" then
    print(child:source())
  elseif child:type() == "function_declaration" then
    -- 遍历第一层的子元素
    for child2 in child:children() do
      if child2:type() == "identifier" then
        -- 打印'function' + 函数名
        io.write("function " .. child2:source() .. "(")
      elseif child2:type() == "parameter_list" then
        local params = {}
        for child4 in child2:children() do
          if child4:type() == "parameters" then
            for child5 in child4:children() do
              if child5:type() == "parameter" then
                local iden = child5:named_child(0)
                table.insert(params, iden:source())
              end
            end
          end
        end
        -- 打印参数列表，用逗号分隔
        io.write(table.concat(params, ", ") .. "){}")
      end
    end
    io.write("\n")
    --print(child:source())
  else
    -- print(child:type())
  end
end
